﻿using FakeItEasy;
using Sustainalytics.Claims;
using Sustainalytics.DataLayer;
using Sustainalytics.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using Xunit;

namespace Sustainalytics.ClaimsService.Tests
{
    public class ExcelClaimsModifierTest
    {
        [Fact]
        public void ReadXLS()
        {
            var book = SpreadsheetGear.Factory.GetWorkbook(@"..\..\Templates\upload_template.xlsx");
            var claimsData = book.Worksheets[3].Cells;

            Assert.Equal("Screening tool - ESG performance - Governance subtab", claimsData[1, 0].Text);
        }

        [Fact]
        public void ConvertXLStoClaimsOnlyTab3()
        {
            TestParseExcel(false);
        }

        [Fact]
        public void ConvertXLStoClaimsAllTabs()
        {
            TestParseExcel(true);
        }

        private readonly Dictionary<Guid, string> _dictAccounts = new Dictionary<Guid, string>() {
            { new Guid("528ea769-2d17-e411-92ce-6c3be5be9f98"), "Sustainalytics Toronto" },
            { new Guid("596d5f79-9748-e411-9e5f-d89d67630ddc"), "Sustainalytics" },
            { new Guid("e0b461fc-6012-e211-9a22-3c4a92dbc8a2"), "AMD" },
            { new Guid("af43e421-a802-e411-a08b-6c3be5be2f78"), "ANWB Beheer" },
            { new Guid("0744e421-a802-e411-a08b-6c3be5be2f78"), "Aviva Investors" },
            { new Guid("e2b261fc-6012-e211-9a22-3c4a92dbc8a2"), "AFL-CIO" },
            { new Guid("33f1bd20-bf31-e411-96ee-6c3be5be9f98"), "Share Account" },
            { new Guid("2b43e421-a802-e411-a08b-6c3be5be2f78"), "ABN AMRO NV" },
            { new Guid("b1c2e081-e5ad-e211-89a7-3c4a92dbd83d"), "ACM Advisors" }
        };

        private void TestParseExcel(bool processAll)
        {
            var operationClaimsRetriever = A.Fake<IOperationClaimsRetriever>();

            var accountRepository = A.Fake<IAccountsRepository>();
            A.CallTo(() => accountRepository.GetAccountById(A<Guid>._)).ReturnsLazily((Guid call) => { return _dictAccounts.ContainsKey(call) ? new Account() { Id = call, Name = _dictAccounts[call] } : null; });

            var mod = new ExcelClaimsModifier(operationClaimsRetriever, id => accountRepository.TryGetAccountById(id));

            mod.ParseExcel(File.ReadAllBytes(@"..\..\Templates\upload_template.xlsx"), processAll);

            A.CallTo(() => operationClaimsRetriever.AddResourceMap(A<List<ResourceMap>>.Ignored)).MustHaveHappened();
            if (processAll)
                A.CallTo(() => operationClaimsRetriever.AddClaims(A<Entities.Claims>.Ignored)).MustHaveHappened();
            else
                A.CallTo(() => operationClaimsRetriever.AddClaims(A<Entities.Claims>.Ignored)).MustNotHaveHappened();
        }
    }
}
